﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using Windows.ApplicationModel;
using Windows.ApplicationModel.DataTransfer;
using Windows.Data.Xml.Dom;
using Windows.Storage.Streams;

namespace SuperQuiz.Model
{
    public class QuizQuestion : BindableBase
    {
        private Quiz _Quiz;
        [IgnoreDataMember]
        public Quiz Quiz
        {
            get { return this._Quiz; }
            set { this.SetProperty(ref this._Quiz, value); }
        }

        private string _Code;
        public string Code
        {
            get { return this._Code; }
            set { this.SetProperty(ref this._Code, value); }
        }

        private string _Title;
        public string Title
        {
            get { return this._Title; }
            set { this.SetProperty(ref this._Title, value); }
        }

        private string _SubTitle;
        public string SubTitle
        {
            get { return this._SubTitle; }
            set { this.SetProperty(ref this._SubTitle, value); }
        }

        private string _Description;
        public string Description
        {
            get { return this._Description; }
            set { this.SetProperty(ref this._Description, value); }
        }

        private string _ImageUri;
        public string ImageUri
        {
            get { return this._ImageUri; }
            set { this.SetProperty(ref this._ImageUri, value); }
        }

        private ObservableCollection<QuizUriLink> _Links = new ObservableCollection<QuizUriLink>();
        public ObservableCollection<QuizUriLink> Links
        {
            get { return this._Links; }
            set { this.SetProperty(ref this._Links, value); }
        }

        private ObservableCollection<QuizAnswer> _Answers;
        public ObservableCollection<QuizAnswer> Answers
        {
            get { return this._Answers; }
            set { this.SetProperty(ref this._Answers, value); }
        }

        public override string ToString()
        {
            var text = new StringBuilder();
            text.AppendLine(String.Format("{0}", Title));
            text.AppendLine();
            text.AppendLine(String.Format("{0}", Description));
            text.AppendLine();
            var i = (byte)'A';
            foreach (var answer in Answers)
            {
                text.AppendLine(String.Format("{0}) {1}", (char)i++, answer.Name));
                text.AppendLine(String.Format("{0}", answer.Description));
                text.AppendLine();
            }
            return text.ToString();
        }

        public async Task FillDataPackage(DataPackage requestData)
        {
            FillDataPackageWithText(requestData);
            await FillDataPackageWithHtml(requestData);
        }

        private async Task FillDataPackageWithHtml(DataPackage requestData)
        {
            var xml = new XmlDocument();
            var body = xml.CreateElement("DIV");
            xml.AppendChild(body);

            var quizName = xml.CreateElement("H1");
            quizName.InnerText = Quiz.Name;
            body.AppendChild(quizName);

            var questionName = xml.CreateElement("H2");
            questionName.InnerText = Title;
            body.AppendChild(questionName);

            var quizDescription = xml.CreateElement("P");
            quizDescription.InnerText = Description;
            body.AppendChild(quizDescription);

            body.AppendChild(await CreateImageHtmlDataPackage(ImageUri, requestData, xml));

            var quizAnswers = xml.CreateElement("OL");
            quizAnswers.SetAttribute("style", "list-style-type:upper-alpha");
            body.AppendChild(quizAnswers);

            var i = (byte)'A';
            foreach (var answer in Answers)
            {
                var quizAnswer = xml.CreateElement("LI");
                quizAnswers.AppendChild(quizAnswer);

                if (!string.IsNullOrEmpty(answer.Name))
                {
                    var quizAnswerName = xml.CreateElement("DIV");
                    quizAnswerName.InnerText = answer.Name;
                    quizAnswer.AppendChild(quizAnswerName);
                }

                if (!string.IsNullOrEmpty(answer.Description))
                {
                    var quizAnswerDescription = xml.CreateElement("DIV");
                    quizAnswerDescription.InnerText = answer.Description;
                    quizAnswer.AppendChild(quizAnswerDescription);
                }

                if (!string.IsNullOrEmpty(answer.ImageUri))
                {
                    quizAnswer.AppendChild(await CreateImageHtmlDataPackage(answer.ImageUri, requestData, xml));
                }
            }
            requestData.SetHtmlFormat(HtmlFormatHelper.CreateHtmlFormat(xml.GetXml()));
        }

        private async Task<IXmlNode> CreateImageHtmlDataPackage(string imageUri, DataPackage requestData, XmlDocument xmlDocument)
        {
            if (!string.IsNullOrEmpty(ImageUri))
            {
                try
                {
                    var fileName = String.Format("img{0}{1}", requestData.ResourceMap.Count, Path.GetExtension(ImageUri));
                    var questionImage = xmlDocument.CreateElement("IMG");
                    questionImage.SetAttribute("SRC", fileName);
                    var file = await Package.Current.InstalledLocation.GetFileAsync(ImageUri.Replace("/", @"\"));
                    var streamRef = RandomAccessStreamReference.CreateFromFile(file);
                    requestData.ResourceMap[fileName] = streamRef;
                    return questionImage;
                }
                catch { }
            }
            return xmlDocument.CreateTextNode("");
        }

        private void FillDataPackageWithText(DataPackage requestData)
        {
            var text = new StringBuilder();
            text.AppendLine(String.Format("{0}", Quiz.Name));
            text.AppendLine(String.Format("{0}", ToString()));
            requestData.SetText(text.ToString());
        }
    }
}
